//
//  LBNetworkTools.swift
//  LBNewWeiBo
//
//  Created by bin on 15/10/29.
//  Copyright © 2015年 bin. All rights reserved.
//

import UIKit
import AFNetworking

//MARK: - 网络错误枚举
enum LBNetworkError: Int {
    case emptyToken = -1 // acceccToken 为空
    case emptyUid = -2 // Uid 为空
    
    /// 定义打印错误的属性
    var description: String {
        get {
            switch self {
            case LBNetworkError.emptyToken:
                return "acceccToken:为空"
            case LBNetworkError.emptyUid:
                return "Uid:为空"
            }
        }
    }
    
    // 错误方法
    func error() -> NSError {
        return NSError(domain: "cn.binshui.error,network", code: rawValue, userInfo: ["errorDescription" : description])
    }
    
}

class LBNetworkTools: NSObject {
    ///请求属性
    private var afnManager: AFHTTPSessionManager
    
    static let sharedInstance: LBNetworkTools = LBNetworkTools()
    
    override init() {
        let urlString = "https://api.weibo.com/"
        afnManager = AFHTTPSessionManager(baseURL: NSURL(string: urlString))
        afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
    
    }
    
    //MARK: -oauth授权
    // 申请时分配的 App Key：
    private let client_id = "3807849249"
    
    // 申请时分配的 App Secret：授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址。
    private let client_secret = "72b6927a36f758e0bf21d0c1421aa2dc"
    // 请求的类型，填写authorization_code
    private let grant_type = "authorization_code"
//    	回调地址，需需与注册应用里的回调地址一致。
    let redirect_uri = "http://www.baidu.com"
    
    /// OAtuhURL地址拼接的方法
    func oauthRUL() -> NSURL {
    // 拼接地址
         let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        return NSURL(string: urlString)!
    }
    
    // 使用闭包回调
    // MARK: - 加载 access_token
    func loadAccessToKen(code: String, finshed: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        // url
        let urlString = "oauth2/access_token"
        
        // 参数
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": grant_type,
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        // 请求结果
        afnManager.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            // 请求成功，回调闭包
            finshed(result: result as? [String: AnyObject], error: nil)
            
            }) { (_, error: NSError) -> Void in
                // 请求失败
                finshed(result: nil, error: error)
        }
    }
    
    //MARK: - 获取用户信息
    func loadUserInfo(finished:NetworkFinishedCallback) {
        
//        // 判断用户的Access token
//        if LBUserAccout.loadAccount()?.access_token == nil {
//            print("没有access_token")
//            return
//        }
        
        // 守卫。和可选绑定相反
        // parameters 代码块里面和外面都可以使用
        guard var parameters = tokenDict() else {
            // 表示parameters没有值
            let error = LBNetworkError.emptyToken.error()
            
            // 告诉调用者
            finished(result: nil, error: error)
            return
        }
        
        
        // 判断uid
        if LBUserAccout.loadAccount()?.uid == nil {
           // 没有uid
            let error = LBNetworkError.emptyUid.error()
            finished(result: nil, error: error)
            return
        }
            // 用户信息的url
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        // 添加元素
        parameters["uid"] = LBUserAccout.loadAccount()!.uid!
        
        // 请求用户信息
        requestGET(urlStr, parameters: parameters, finshed: finished)
        
    }
    
    //MARK: - 判断token是否有值,如果有就生成一个字典
    func tokenDict() -> [String: AnyObject]? {
        if LBUserAccout.loadAccount()?.access_token == nil {
            return nil
        }
        // 返回字典
        return ["access_token": LBUserAccout.loadAccount()!.access_token!]
    }
    
    
    //MARK: - 获取微博数据
    func loadStatus(finished: NetworkFinishedCallback) {
        
//        if let accessToken = LBUserAccout.loadAccount()?.access_token {
//            print("access_token有值")
//            
//            let urlString = "2/statuses/home_timeline.json"
//             let parameters = ["access_token":accessToken]
//            
//            requestGET(urlString, parameters: parameters, finshed: finished)
//        }
        
        
        // 守卫
        guard let parametes = tokenDict() else {
            // 没有值
            // 告诉调用者
            finished(result: nil, error: LBNetworkError.emptyToken.error())
            return
        }
        
        // eccess token 说明有值
        let userStr = "2/statuses/home_timeline.json"
        
        // 加载本地文件
        loadLocalStatus(finished)
        
        // 网络请求
//        requestGET(userStr, parameters: parametes, finshed: finished)
    }
    
    /// 加载本地微博数据
    private func loadLocalStatus(finished: NetworkFinishedCallback) {
        // 获取路径
      let path =  NSBundle .mainBundle().pathForResource("statuses", ofType: "json")
        
        // 加载本地数据
       let data = NSData(contentsOfFile: path!)
        
        // 转换json
        do {
            
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue:0))
            
            // 有数据
            finished(result: json as? [String: AnyObject], error: nil)
        }catch {
            print("出异常了")
        }
        
    }
    
    
    
    
    
        /// 类型别名 = typealias
        typealias NetworkFinishedCallback = (result: [String :AnyObject]?, error: NSError?) ->()
    
        //MARK: - 封装AFN.GET
    func requestGET(URLString: String, parameters: AnyObject?, finshed: NetworkFinishedCallback) {
        
        afnManager.GET(URLString, parameters: parameters, success: { (_, result) -> Void in
            finshed(result: result as? [String: AnyObject], error: nil)
            }) { (_, error) -> Void in
                finshed(result: nil, error: error)
        }
    }
}




